#include "SocketImpl.h"
#include "Constants.h"

#include <log4cpp/Category.hh>
#include <arpa/inet.h>

#include <string.h>
#include <sstream>

namespace SocketImp {

log4cpp::Category& logger =
    log4cpp::Category::getInstance(std::string(SERVER_LOGGER));



int createServerSocket(){

  LOG_DEBUG("createServerSocket->In");

  struct sockaddr_in serv_addr;//, cli_addr;

  /* First call to socket() function */
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0)
  {
    char* buffer = strerror(errno);//TODO need to change to thread safe one
    LOG_ERROR(buffer);
    throw std::runtime_error(std::string("socket init failed: ") + buffer );
  }
  /* Initialize socket structure */
  bzero((char *) &serv_addr, sizeof(serv_addr));
  //TODO
  int portno = 5001;
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(portno);

  /* Now bind the host address using bind() call.*/
  if (bind(sockfd, (struct sockaddr *) &serv_addr,
      sizeof(serv_addr)) < 0)
  {
    char* buffer = strerror(errno);//TODO
    LOG_ERROR(buffer);
    throw std::runtime_error(std::string("socket bind failed: ") + buffer );
  }

  /* Now start listening for the clients, here process will
   * go in sleep mode and will wait for the incoming connection
   */
  listen(sockfd,10);

  return sockfd;
}


int getNewConnection(int sockfd,
                     unsigned int& clientPort,
                     std::string& ipAddr) {

  LOG_DEBUG("getNewConnection->In");

  struct sockaddr_in cli_addr;
  memset(&cli_addr, 0, sizeof(struct sockaddr_in));
  socklen_t clilen = sizeof(struct sockaddr_in);

  LOG_DEBUG("createServerSocket:: Waiting for connection");
  /* Accept actual connection from the client */
  int newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr,
      &clilen);
  if (newsockfd < 0)
  {
    char* buffer = strerror(errno);//TODO
    LOG_ERROR(buffer);
    throw std::runtime_error(std::string("socket accept failed: ") + buffer );
  }


  if (cli_addr.sin_family == AF_INET) {

    clientPort = cli_addr.sin_port;
    char str[INET6_ADDRSTRLEN];
    inet_ntop(AF_INET, &cli_addr.sin_addr, str, INET6_ADDRSTRLEN);
    ipAddr = str;

  }
  else if (cli_addr.sin_family == AF_INET6) {
    //TODO
    LOG_DEBUG("IP6 connection");

  }
  std::stringstream ss;
  ss<< "IP4 connection IP: "<<ipAddr<< ":"<<clientPort;
  LOG_DEBUG(ss.str());

  LOG_DEBUG("getNewConnection->Out");
  return newsockfd;
}

int readData(int fd, std::stringstream& ss) {

  char buffer[RECV_SIZE];
  memset(buffer, 0, RECV_SIZE);
  ssize_t n = read( fd, buffer, RECV_SIZE );
  if (n<0) {// error condition

    char* buffer = strerror(errno);
    LOG_ERROR(buffer);

    throw std::runtime_error(std::string("socket read failed: ") + buffer );
  }
  ss<<buffer;
  return n;
}


int writeData(int fd, const std::string& ss) {

  ssize_t n = write( fd, ss.c_str(), ss.length() );
  if (n<0) {// error condition

    char* buffer = strerror(errno);
    LOG_ERROR(buffer);

    throw std::runtime_error(std::string("socket write failed: ") + buffer );
  }
  return n;
}


}
